package com.shop.user.api.api;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.user.model.Account;
import com.shop.user.model.User;
import com.shop.user.model.search.UserSearchBean;
import com.shop.user.service.UserService;
import com.wf.captcha.SpecCaptcha;
import com.zijie.core.util.JsonResult;
import com.zijie.core.util.JwtUtils;
import jakarta.servlet.http.HttpServletResponse;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RefreshScope
@RestController
@RequestMapping("/api/v1/user")
public class UserApi {
    private UserService userService;
    private RedisTemplate<String,Object> redisTemplate;
    private static StrongPasswordEncryptor PE = new StrongPasswordEncryptor();
    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/captcha")
    public void captcha(String id, HttpServletResponse resp) throws IOException {
        System.out.println("验证码");
        SpecCaptcha captcha = new SpecCaptcha(140, 40, 4);
        resp.setContentType("image/gif");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        redisTemplate.opsForValue().set("captcha-"+id,
                captcha.text().toLowerCase(), Duration.ofMinutes(3));
        captcha.out(resp.getOutputStream());
    }
    @PostMapping("/login")
    public ResponseEntity<JsonResult<?>> login(@RequestBody Account account) {
        System.out.println("登录");
        String correct = (String) redisTemplate.opsForValue().get("captcha-"+account.getCaptchaId());
        if (!account.getCaptcha().equals(correct)) {
            System.out.println(correct);
            System.out.println(account.getCaptcha());
            return ResponseEntity.ok(JsonResult.error("验证码不正确"));
        }

        User user = userService.findByInput(account.getUsername());
        if (user == null) {
            return ResponseEntity.ok(JsonResult.error("用户不存在"));
        }
        if (!user.getEnabled()) {
            return ResponseEntity.ok(JsonResult.error("用户被禁用"));
        }

        //校验密码
        boolean pass = PE.checkPassword(account.getPassword(), user.getPassword());
        if (!pass) {
            return ResponseEntity.ok(JsonResult.error("密码不正确"));
        }
        //存储用户信息
        Map<String, Object> map = new HashMap<>();
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        String token = JwtUtils.generateJwt(map);
        user.setToken(token);
        System.out.println("111"+token);
        return ResponseEntity.ok(JsonResult.success(user));
    }
    @GetMapping
    public ResponseEntity<JsonResult<?>> findAll(
            @RequestParam(defaultValue = "1")Integer pageNo,
            @RequestParam(defaultValue = "10")Integer pageSize,
            UserSearchBean usb
    ){
        Page<User> page = Page.of(pageNo, pageSize);
        page=userService.findAll(page, usb);
        return ResponseEntity.ok(JsonResult.success(page));
    }
    @GetMapping("/findById/{id}")
    public ResponseEntity<JsonResult<?>> findById(@PathVariable Integer id) {
        User user = userService.findById(id);
        if (user == null) {
            return ResponseEntity.ok(JsonResult.error("未找到该用户"));
        }
        return ResponseEntity.ok(JsonResult.success(user));
    }
    @PostMapping("/save")
    public ResponseEntity<JsonResult<?>> save(@RequestBody User user) {
        boolean b = userService.save(user);
        if (!b) {
            return ResponseEntity.ok(JsonResult.error("保存失败"));
        }
        return ResponseEntity.ok(JsonResult.success("保存成功"));
    }
    @PostMapping("/add")
    public ResponseEntity<JsonResult<?>> add(@RequestBody User user) {
        int b = userService.add(user);
        if (b==0) {
            return ResponseEntity.ok(JsonResult.error("更新失败"));
        }else if(b==2){
            return ResponseEntity.ok(JsonResult.error("用户名已存在"));
        }
        return ResponseEntity.ok(JsonResult.success("更新成功"));
    }
    @PutMapping("/update")
    public ResponseEntity<JsonResult<?>> update(@RequestBody User user) {
        int b = userService.update(user);
        if (b==0) {
            return ResponseEntity.ok(JsonResult.error("更新失败"));
        }else if(b==2){
            return ResponseEntity.ok(JsonResult.error("用户名已存在"));
        }
        return ResponseEntity.ok(JsonResult.success("更新成功"));
    }
    @PutMapping("/updateEnabled")
    public ResponseEntity<JsonResult<?>> updateEnabled(@RequestBody User user) {
        boolean b = userService.updateEnabled(user);
        if (!b) {
            return ResponseEntity.ok(JsonResult.error("更新失败"));
        }
        return ResponseEntity.ok(JsonResult.success("更新成功"));
    }
    @PutMapping("/updateLocked")
    public ResponseEntity<JsonResult<?>> updateLocked(@RequestBody User user) {
        boolean b = userService.updateLocked(user);
        if (!b) {
            return ResponseEntity.ok(JsonResult.error("更新失败"));
        }
        return ResponseEntity.ok(JsonResult.success("更新成功"));
    }
    @DeleteMapping("/deleteByIds")
    public ResponseEntity<JsonResult<?>> delete(@RequestBody List<Integer> ids) {
        int count = userService.deleteByIds(ids);
        if (count==0){
            return ResponseEntity.ok(JsonResult.error("未找到该用户"));
        }else {
            return ResponseEntity.ok(JsonResult.success(count));
        }
    }
    @DeleteMapping("/deleteById")
    public ResponseEntity<JsonResult<?>> deleteById(@RequestParam Integer id) {
        int count = userService.deleteById(id);
        if (count==0){
            return ResponseEntity.ok(JsonResult.error("未找到该用户"));
        }else {
            return ResponseEntity.ok(JsonResult.success(count));
        }
    }
    @PostMapping("/assignUser")
    public ResponseEntity<JsonResult<?>> assignUser(@RequestBody User user) {
        int count = userService.assignUser(user);
        if (count==0){
            return ResponseEntity.ok(JsonResult.error("未找到该用户"));
        }else {
            return ResponseEntity.ok(JsonResult.success(count));
        }
    }
}
